#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import webapp2
import jinja2
import time #para delay do password

jinja_environment = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
	extensions=['jinja2.ext.autoescape'],
	autoescape=True)

#para banco de dados
from google.appengine.ext import db

#para email
from google.appengine.api import mail



html = """
<!doctype=html>
<html>
<head>
<meta charset="utf-8"/>
<title>Foca+</title>
<link rel="icon" href="/imagens/favicon.ico" type="image/x-icon" />
</head>
<body>
<div id="content" align="center">
<img border="0" align="middle" src="imagens/foca.jpg" alt="Pulpit rock">
<p>Foca+</p>
<h1>Login</h1>
	<form method="post">
		<label for="first_name">Login:</label>
		<input name="first_name" type="text" value=""><br>
		
		<label for="last_name">Senha:</label>
		<input name="last_name" type="password" value=""><br>
		
		<input name="" type="submit" value="Enviar">
	</form>
		<a href="inscrever">Inscrever-se</a><br />
		<a href="esquecer">Esqueci a senha</a><br />
"""

htmlinicio = """
<html>
<head></head>
<body>
<div align="center">
"""


htmlfim = """
</div>
</body>
</html>
"""

html2 = """
<html>
<head>
</head>
<body>
<div id="content" align="center">
<p>Foca+</p>
<h1>Increva-se</h1>
<h1>Login</h1>
	<form method="post">
		<label for="first_name">Escolha um Usuario:</label>
		<input name="first_name" type="text" value=""><br>
		
		<label for="last_name">Escolha uma Senha:</label>
		<input name="last_name" type="password" value=""><br>
		
		<label for="email">Escolha um e-mail:</label>
		<input name="email" type="email" value=""><br>
		
		<input name="" type="submit" value="Enviar">
	</form>
"""

htmlSenha = """
<h1>Escreva seu email e enviaremos sua senha</h1>
	<form method="post">
		<label for="email">Escolha um e-mail:</label>
		<input name="email" type="email" value=""><br>
		
		<input name="" type="submit" value="Enviar">
	</form>
"""
  


class Employee(db.Model):
	first_name = db.StringProperty()
	last_name = db.StringProperty()
	
	email = db.EmailProperty()
	chave = db.Key()
	

  
class MainHandler(webapp2.RequestHandler):
	def get(self):
		self.response.write(html)
		
		# funciona
		#self.response.set_cookie('senha', 'tiltdoido')
		#teste = self.request.cookies.get('senha')
		#fim funciona
		
		#limpa cookie
		self.response.set_cookie('user_id', '')
		
		#first_name = self.request.get("first_name")
		#last_name = self.request.get("last_name")
		#email = self.request.get("email")
	
		#funciona atualiza com ID
		#myKey = db.Key.from_path('Employee', 5891733057437696)
		#rec = db.get(myKey)
		#rec.first_name = 'Rabujento'
		#rec.put()
		#fim funciona
		
		#funciona
		#q = db.GqlQuery("SELECT * FROM Employee")
		#for self.employee in q.run():
		#	nome = self.employee.first_name
		#	senha = self.employee.last_name
		#	emeiu = self.employee.email
		#	idi = self.employee.key().id_or_name() #id_or_name()
		#	self.response.write('%s %s %s %s<br />' % (nome, senha, emeiu, idi))
			#fim do funciona
			
			
		#rob = Employee(chave = "123", first_name = 'mazute')
		#rob.put()
			
			
			# funciona
			#rob = Employee(key_name = ('%s' % aidih), first_name = 'mazute')
			#rob.put()
			# fim do funciona
			
			#if aidih
			#	rob.delete()
			
			#fim funciona
			
			#busca e apaga ok ---- para excluir cadastro
			#q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = 'Sapolino'") #'Bob'"
			#for self.employee in q.run():
			#	self.employee.delete()
			#fim do busca e apaga
			
			#incluir funciona ok
			#rob = Employee(key_name='6578378068983808')
			#rob.first_name = "Sapolino"
			#rob.put()
			#fim do incluir
			
			#apaga funciona
			#rob = Employee(key_name='6578378068983808')
			#rob.delete()
			#fim apaga funciona
			 
#        self.query = Employee.all()
 #       self.query.filter("first_name =", "Bob")
  #      for self.employee in self.query:
	#		self.response.write('<p>%s</p>' % self.employee.first_name)
	
        #q = Employee.all()
    #q.order("-first_name")
        
		#funciona
		#q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = 'Bob'")
        #result = q.get()
        #self.response.write(result)	
        
		#for p in q.run():
        # print p.last_name
 #       result = q.get()
  #      print Employee.first_name
		self.response.write(htmlfim)
		
	def post(self):		
		first_name1 = self.request.get("first_name")
		last_name1 = self.request.get("last_name")
		#self.response.out.write("Login: " + first_name1 + " Senha: " + last_name1 + "\n")
		
		# incrementa banco de dados
#		employee = Employee(first_name=first_name,
#                    last_name=last_name)
#		employee.put()

		#
		self.response.set_cookie('user_id', first_name1)
		
		#self.query = Employee.all()
		#self.query.filter("first_name =", "Bob")
		if(first_name1 == '' or last_name1 == ''):
			self.response.write(html)
			self.response.write('Escreva um nome e/ou uma senha!<br />')
		else:
			nome = ''
			sobrenome = ''
			q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = :1" , first_name1) #'Bob'"
			for self.employee in q.run(limit=4):
				#self.response.write('<p>%s</p>' % self.employee.last_name)
				nome = self.employee.first_name
				sobrenome = self.employee.last_name
				#tilt = self.request.cookies.get('user_id')
			if nome == first_name1 and sobrenome == last_name1:
				#self.response.write(htmlinicio)
				#self.response.write('<br />Bem Vindo %s' % nome)
				#self.redirect("/bemvindo")
				
				#time.sleep(2) # delays for 5 seconds
				
				self.redirect("/bemvindo")
				
				
			else:
				self.response.write(html)
				self.response.write('<br />Login e/ou Senha Invalido(s)')	
		self.response.write(htmlfim)

class Inscrever(webapp2.RequestHandler):
	def get(self):
		
		self.response.write(html2)
		self.response.write('<a href="/">Voltar</a>')
		self.response.write(htmlfim)
	def post(self):
		self.response.write(html2)
		#incrementa banco de dados
		first_name = self.request.get("first_name")
		last_name = self.request.get("last_name")
		email = self.request.get("email")
		
		nome = ''
		
		if(first_name == '' or last_name == '' or email ==''):
			self.response.write('Escreva um nome e/ou uma senha e/ou e-mail!<br />')
		else:
			q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = :1" , first_name)
			for self.employee in q.run(limit=4):
				nome = self.employee.first_name			
			if nome == first_name:
				self.response.write('O login %s nao esta disponivel, escolha outro!<br />' % nome)
			else:
				employee = Employee(first_name=first_name, #key_name='sapolao',
				last_name=last_name, email=email)
				employee.put()
				self.response.write('<p>Gravado!!!!!!!!!!!!!!!!!!!!!!!</p>')
		self.response.write('<a href="/">Voltar</a>')
		self.response.write(htmlfim)

class Esquecer(webapp2.RequestHandler):
	def get(self):
		self.response.write(htmlinicio)
		self.response.write(htmlSenha)
		self.response.write('<br /><a href="/">Inicio</a><br />')
		self.response.write(htmlfim)
	def post(self):
		tememail = 0
		self.response.write(htmlinicio)
		email = self.request.get("email")
		
		if not mail.is_email_valid(email):
			self.response.write(htmlSenha)
			self.response.write('Escreva um e-mail valido!<br />')
		else:
			q = db.GqlQuery("SELECT * FROM Employee WHERE email = :1" , email)
			for self.employee in q.run():
				mail.send_mail('betojasz@gmail.com', email, 'Senha', 'Seu login e: %s \r\nSua senha eh: %s' % (self.employee.first_name,self.employee.last_name))
				tememail = 1
			if tememail == 0:
				self.response.write('Este e-mail nao esta cadastrado<br />')
				self.response.write('<a href="/esquecer">Voltar</a><br />')
				#self.response.write('<a href="/esquecer">Tentar novamente</a><br />')
			else:
				self.response.write('<p>Sua senha chegara nos proximos minutos em seu email!</p>')
		self.response.write('<br /><a href="/">Inicio</a><br />')
		self.response.write(htmlfim)
		
		
class Bemvindo(webapp2.RequestHandler):
	def get(self):
		#recupera login
		tilt = self.request.cookies.get('user_id')
		
		#caso nao haja um login, nao abre
		if tilt == "":
			self.redirect("/")
		else:
			#passa = self.request.cookies.get('senha')
			
			#time.sleep(2) # delays for 5 seconds
					
			template_values = {
			'name': tilt,
			#'verb': passa
			}
			template = jinja_environment.get_template('teste.html')
			self.response.write(template.render(template_values))
					
			
			#self.response.write(htmlinicio)
			#self.response.write('<h1>Bem vindo!</h1>')
			#self.response.write('<b>Configuracoes!</b><br />')
			#self.response.write('Mudar senha!<br />')
			#self.response.write('Excluir cadastro!<br />')
			#self.response.write(htmlfim)

class Excluir(webapp2.RequestHandler):		
	def get(self):
		#recupera id do cookie
		tilt = self.request.cookies.get('user_id')
		
		#descobre id do banco de dados
		q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = :1", tilt)		
		for self.employee in q.run():
			idi = self.employee.key().id_or_name() #id_or_name()
		
		#recupera id no banco de dados
		myKey = db.Key.from_path('Employee', idi)
		rob = db.get(myKey)
		
		#apaga
		rob.delete()
		
		self.response.write(htmlinicio)
		self.response.write("Excluido<br />")
		self.response.write("<a href=\"/\">Voltar</a><br />")
		self.response.write(htmlfim)

class Mudar(webapp2.RequestHandler):
	def get(self):
		#template_values = {
		#'name': tilt,
		#'verb': passa
		#}
		
		template = jinja_environment.get_template('mudar.html')
		self.response.write(template.render())
		self.response.write(htmlfim)
		
	def post(self):
		#pega a senha digitada
		last_name = self.request.get("last_name")
		
		if last_name == "":
			template = jinja_environment.get_template('mudar.html')
			self.response.write(template.render())
			self.response.write("Escreva uma senha!!<br />")
			self.response.write(htmlfim)
		else:

		
			#recupera id do cookie
			tilt = self.request.cookies.get('user_id')
		
			#descobre id do banco de dados
			q = db.GqlQuery("SELECT * FROM Employee WHERE first_name = :1", tilt)		
			for self.employee in q.run():
				idi = self.employee.key().id_or_name() #id_or_name()
		
			#recupera id no banco de dados
			myKey = db.Key.from_path('Employee', idi)
			rec = db.get(myKey)
			rec.last_name = last_name
			rec.put()
		
			self.response.write(htmlinicio)
			self.response.write("Senha alterada com sucesso!!<br />")
			self.response.write("<a href=\"/bemvindo\">Voltar</a><br />")
			self.response.write("<a href=\"/\">Inicio</a><br />")
			self.response.write(htmlfim)

class Sair(webapp2.RequestHandler):
	def get(self):
		self.response.set_cookie('user_id', '')
		self.redirect("/")
	
app = webapp2.WSGIApplication([
    ('/', MainHandler),
	('/inscrever',Inscrever),
	('/esquecer',Esquecer),
	('/bemvindo',Bemvindo),
	('/excluir',Excluir),
	('/mudar',Mudar),
	('/sair',Sair)
], debug=True )

